//
//  HELSearchVC.m
//  sanda
//
//  Created by wsj2015 on 16/7/11.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "HELSearchVC.h"
#import "HELDataCommonCell.h"
#import "HELCourseDetailVC.h"
#import "UISearchBar+VDInnerComponents.h"
#import "HELNetworkManager.h"
#import "HELSearchResultsModel.h"
#import "Masonry.h"
#import "HELTypeChooseVC.h"
#import <UITableView+FDTemplateLayoutCell.h>
#import "HELCourseTypeChooseVC.h"
static NSInteger currentPage = 1;

@interface HELSearchVC ()<UISearchBarDelegate>
@property (nonatomic,  strong) UISearchBar *searchBar;

@property (nonatomic,  strong) UIView *chooseView;


@property (nonatomic,  strong) UIView *courseTypeView;


@property (nonatomic,  strong) NSString *departmentNo;

@property (nonatomic,  assign) NSInteger studyType;


@end

@implementation HELSearchVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
   
    
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.studyType = -1;
    }
    return self;
}
-(UIView *)chooseView{
    if (!_chooseView) {
       
        _chooseView = [UIView new];
        _chooseView.backgroundColor =kAppBg;
        _chooseView.layer.borderWidth = 1;
        _chooseView.layer.borderColor = kMainColor.CGColor;
        UILabel *label =[UILabel new];
        label.text = @"科室筛选";
        label.tag = 201;
        [_chooseView addSubview:label];
        UIImageView *imageView =[UIImageView new];
        imageView.image =[UIImage imageNamed:@"search_choose"];
        [_chooseView addSubview:imageView];
        UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseDepartment:)];
        _chooseView.userInteractionEnabled = YES;
        [_chooseView addGestureRecognizer:tap];
        
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_chooseView.mas_left).offset(10);
            make.top.equalTo(_chooseView.mas_top).offset(12);
        
        }];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(13);
            make.height.mas_equalTo(16);
            make.left.equalTo(label.mas_right).offset(6);
            make.top.equalTo(_chooseView.mas_top).offset(14);
        }];
        
//        UIButton *btn =[UIButton buttonWithType:UIButtonTypeCustom];
//        btn.frame =CGRectMake(0, 0, kScreenWidth, 33);
//        [btn setBackgroundColor:[UIColor blueColor]];
//        [btn addTarget:self action:@selector(chooseDepartment) forControlEvents:UIControlEventTouchUpInside];
//        [_chooseView addSubview:btn];
    }
    return _chooseView;
}

- (UIView *)courseTypeView{
    if (!_courseTypeView) {
        _courseTypeView =[UIView new];
        UILabel *label =[UILabel new];
        label.tag = 700;
        label.text = @"全部";
//        label.frame =CGRectMake(8, 10, 200, 20);
        [_courseTypeView addSubview:label];
        
        UILabel *label2 =[UILabel new];
        label2.tag = 701;
        label2.text = @"全部";
        [_courseTypeView addSubview:label2];
        
        
        UIImageView *indeimg =[UIImageView new];
        indeimg.image = [UIImage imageNamed:@"type_indecator"];
        [_courseTypeView addSubview:indeimg];
        
        
        UIButton *btn =[UIButton buttonWithType:UIButtonTypeCustom];
//        btn.frame = CGRectMake(kScreenWidth -44, 3, 44, 33);
        [btn setImage:[UIImage imageNamed:@"menu_search"] forState:UIControlStateNormal];
        [_courseTypeView addSubview:btn];
        [btn addTarget:self action:@selector(courseTypeChoose) forControlEvents:UIControlEventTouchUpInside];
        
        
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_courseTypeView).offset(8);
            make.top.equalTo(_courseTypeView).offset(10);
        }];
        [indeimg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(label);
            make.left.equalTo(label.mas_right).offset(8);
            make.width.mas_equalTo(12);
            make.height.mas_equalTo(12);
        }];
        [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(label);
            make.left.equalTo(indeimg.mas_right).offset(8);
            make.right.lessThanOrEqualTo(btn.mas_left);
           
        }];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(_courseTypeView.mas_right);
            make.centerY.equalTo(_courseTypeView.mas_centerY);
            make.width.mas_equalTo(39);
            make.height.mas_equalTo(39);
            
        }];
        
        
        
        
    }
    return _courseTypeView;
}

- (void)courseTypeChoose{
    HELCourseTypeChooseVC *vc =[HELCourseTypeChooseVC new];
    weakSelf_define;
    vc.callBack =  ^(NSDictionary *dict){
        
        UILabel *label =[weakSelf.courseTypeView viewWithTag:701];
        label.text = dict[@"typeName"];
        weakSelf.studyType = [dict[@"id"] integerValue];
        [UIView animateWithDuration:.8 animations:^{
            [weakSelf.courseTypeView layoutIfNeeded];
        }];
        [weakSelf requestSearchDataisRecover:YES];
        
     
    };
    [self.navigationController pushViewController:vc animated:YES];

}




#pragma mark -选择科室....
//- (void)chooseDepartment:(UITapGestureRecognizer *)tap{
//    [self.searchBar resignFirstResponder];
//    self.searchBar.text = @"";
//    HELTypeChooseVC *vc =[HELTypeChooseVC new];
//    weakSelf_define;
//    vc.callBack = ^(NSString *departmentNo,NSString *departmentName){
////        选择的全部
//        if (departmentNo ==nil) {
//            UILabel *label =[weakSelf.chooseView viewWithTag:201];
//            weakSelf.departmentNo = nil;
//            [weakSelf requestSearchDataisRecover:YES];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                label.text =@"全部";
//                [weakSelf.chooseView setNeedsLayout];
//                [weakSelf.chooseView updateConstraintsIfNeeded];
//                [UIView animateWithDuration:.35f animations:^{
//                    [weakSelf.chooseView layoutIfNeeded];
//                } completion:nil];
//            });
//            return ;
//
//        }
//     
//        
//        weakSelf.departmentNo =departmentNo;
//        UILabel *label =[weakSelf.chooseView viewWithTag:201];
//        [weakSelf requestSearchDataisRecover:YES];
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            label.text =departmentName;
//            [weakSelf.chooseView setNeedsLayout];
//            [weakSelf.chooseView updateConstraintsIfNeeded];
//            [UIView animateWithDuration:.35f animations:^{
//                [weakSelf.chooseView layoutIfNeeded];
//            } completion:nil];
//        });
//        
//    };
//    [self.navigationController pushViewController:vc animated:YES];
// 
//}
- (void)configUI{
    
    
    [self.view addSubview:self.tableView];
    self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight -64);
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight =UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 100;
//    [self setNavToBlue];
    self.tableView.tableFooterView = [UIView new];
    [self.tableView registerNib:[UINib nibWithNibName:@"HELDataCommonCell" bundle:nil] forCellReuseIdentifier:@"HELDataCommonCell"];
    self.navigationItem.titleView = self.searchBar;
    
    UIBarButtonItem *rightBtn =[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"搜索"] style:0 target:self action:@selector(searchBarSearchButtonClicked:)];;
    self.navigationItem.rightBarButtonItem = rightBtn;
    
    defineWeakSelf;
    [self.tableView wsj_HeaderRefreshBlock:^{
        [weakSelf requestSearchDataisRecover:YES];
    }];
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf requestSearchDataisRecover:NO];
    }];
    if (self.departmentModel) {
        [self requestSearchDataisRecover:YES];
    }else{
        
        if (self.HELSearchVCType !=HELSearchVCCouresType_hospitalIn) {
             [self.searchBar becomeFirstResponder];
        }
       
    }
    if (self.HELSearchVCType == HELSearchVCCouresType_hospitalIn) {
        [self.view addSubview:self.courseTypeView];
        weakSelf_define;
        [self.courseTypeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(weakSelf.view.mas_left).offset(0);
            make.right.equalTo(weakSelf.view.mas_right).offset(0);
            make.height.mas_equalTo(39);
            make.top.equalTo(weakSelf.view.mas_top).offset(0);
        }];
        UILabel *label = [self.courseTypeView viewWithTag:700];
        label.text =  weakSelf.departmentModel.departmentName;
        
        
        
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.courseTypeView.mas_bottom).offset(0);
            make.left.equalTo(weakSelf.view.mas_left);
            make.right.equalTo(weakSelf.view.mas_right);
            make.bottom.equalTo(weakSelf.view.mas_bottom);
        }];
        
    }
    [self requestSearchDataisRecover:YES];

    
   

}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
//    if (self.HELSearchVCType == HELSearchVCCouresType_hospitalIn) {
//        defineWeakSelf;
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            
//            [weakSelf.view setNeedsLayout];
//            [weakSelf.view updateConstraintsIfNeeded];
//            [self.chooseView mas_updateConstraints:^(MASConstraintMaker *make) {
//                make.top.mas_equalTo(weakSelf.view).offset(-2);
//                
//            }];
//            [weakSelf.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
//                make.top.mas_equalTo(weakSelf.chooseView.mas_bottom).offset(2);
//            }];
//            weakSelf.tableView.contentInset =UIEdgeInsetsMake(0, 0, 0, 0);
//            [UIView animateWithDuration:.35f animations:^{
//                [weakSelf.view layoutIfNeeded];
//            }];
//            
//          
//        });
//       
//        
//    }
}

#pragma mark -查询请求
- (void)requestSearchDataisRecover:(BOOL)isRecover{
    
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
  params[@"hospitalId"] =[HELAppManager userInfo].hospitalId;
    
//    weakSelf_define;
    params[@"keyWordSearch"] =self.searchBar.text;
    
    params[@"pageSize"] = @(10);

    if (isRecover) {
        currentPage =1;
    }else{
        currentPage ++;
    }
    
    params[@"currentPage"] =@(currentPage);
    
    if (self.studyType !=-1) {
        params[@"studyType"] =@(self.studyType);
    }
    
    
//
    //当从院内课程进来的时候
//    if (self.HELSearchVCType == HELSearchVCCouresType_hospitalIn) {
//        if (!self.departmentNo) {
//          
//        }else{
//            params[@"departmentNo"] =self.departmentNo;
//        }
//    }
//    
//    if (self.departmentModel) {
//        params[@"departmentNo"] = self.departmentModel.departmentNo ;
//    }
   
    self.tableView.loading = YES;
    weakSelf_define;
    [[HELNetworkManager sharedMg] POST:kSearchStudyDat_url parameters:params success:^(id responseObject) {
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];
    
        if (isRecover) {
            [weakSelf.dataArray removeAllObjects];
        }
        weakSelf.tableView.loading = NO;
        NSArray *arr =  responseObject[@"rows"];
       
        if ([arr isKindOfClass:[NSArray class]]) {
           
        [weakSelf.dataArray addObjectsFromArray:[HELSearchResultsModel mj_objectArrayWithKeyValuesArray:responseObject[@"rows"]]];
           
        }
        if (weakSelf.dataArray.count<=0) {
            weakSelf.tableView.loading = NO;
        }
        [weakSelf.tableView reloadData];
     
        
        if ([responseObject[@"page"] integerValue] > [responseObject[@"pages"] integerValue]) {
            [weakSelf.tableView.footer noticeNoMoreData];
        }else{
           [weakSelf.tableView.footer resetNoMoreData];
        }
  
    } failure:^(NSString *err) {
        weakSelf.tableView.loading = NO;
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];
       
    }];

}

- (UISearchBar *)searchBar{
    if (!_searchBar) {
        _searchBar =[[UISearchBar alloc] init];
        _searchBar.frame = CGRectMake(0, 0,120, 33);
        _searchBar.delegate = self;
        _searchBar.placeholder =@"搜索平台资料";
        _searchBar.translucent = YES;
        _searchBar.searchBarStyle = UIBarStyleBlackTranslucent;
        UITextField *tf =[_searchBar vd_inputTextField];
        tf.layer.borderWidth = 1;
        tf.layer.borderColor = [UIColor whiteColor].CGColor;
    
        tf.layer.cornerRadius = 14;
        tf.layer.masksToBounds = YES;
        tf.textColor =[UIColor whiteColor];
       [tf setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
        
        [_searchBar showsSearchResultsButton];
        
    }
    return _searchBar;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    if ([self.searchBar.text isEqualToString:@""]||!self.searchBar.text) {
        alertMessage(@"关键字不能为空...");
        return;
    }
    currentPage = 1;
    [self.searchBar endEditing:YES];
    [self requestSearchDataisRecover:YES];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

   return  self.dataArray.count;

}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    weakSelf_define;
//    CGFloat h = [tableView fd_heightForCellWithIdentifier:@"HELDataCommonCell" configuration:^(HELDataCommonCell *cell) {
//         cell.modle = weakSelf.dataArray[indexPath.row];
//    }];
//    return h;
//}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.searchBar endEditing:YES];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HELDataCommonCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HELDataCommonCell" forIndexPath:indexPath];
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = kMainColor;
    bgView.frame =CGRectMake(0, 0, kScreenWidth, 87);
    cell.selectedBackgroundView = bgView;

    cell.modle = self.dataArray[indexPath.row];
    
    return cell;

}



//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    if (self.departmentModel && self.HELSearchVCType !=HELSearchVCCouresType_hospitalIn) {
//        return 39;
//    }
//    return 0;
//}
//-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    if (self.departmentModel && self.HELSearchVCType !=HELSearchVCCouresType_hospitalIn) {
//        return self.departmentModel.departmentName;
//    }
//    return nil;
//    
//
//}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [self.searchBar endEditing:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //进入资料详情

    weakSelf_define;
    HELCourseDetailVC *vc =[HELCourseDetailVC new];
    HELSearchResultsModel *model =  self.dataArray[indexPath.row];
    vc.callBack = ^(HELCourseDetailModel *model){
        [weakSelf requestSearchDataisRecover:YES];
    };
    vc.courseId =[model.id integerValue];
    [self.navigationController pushViewController:vc animated:YES];
}


@end
